/**
 * 客户端使用Ajax技术获取服务端数据
 * 多个para参数必须使用`间隔
 * @author dyh 2011-02-05
 */
package com.zjht.gmcc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zjht.gmcc.bean.util.MyFormat;
import com.zjht.gmcc.bean.util.MyJDBC;
import com.zjht.gmcc.bean.util.MyParam;

public class Ajax extends HttpServlet {

	private static final long serialVersionUID = 1135302774945453643L;

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doAll(request, response);
	}

	private void doAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/xml;charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		request.setCharacterEncoding("GBK");

		// ---参数
		String key = request.getParameter("key");
		if (MyFormat.isStrNull(key))
			return;

		String sql = MyParam.hAjaxSQL.get(key);

		if (MyFormat.isStrNull(sql))
			return;

		int paracount = MyFormat.matchStrCount(sql, "\\?");// 查找SQL中参数数量
		String[] paras = null;
		if (paracount > 0) {
			String para = request.getParameter("para");
			if (MyFormat.isStrNull(para))
				return;
			paras = para.split("`");// 多个para参数必须使用`间隔
			if (paracount != paras.length)// 参数数量不一致
				return;
		}

		MyJDBC myJDBC = null;
		try {
			myJDBC = new MyJDBC();

			PreparedStatement ps = myJDBC.prepareStatement(sql);
			int i = 1;
			if (paras != null) {
				for (String para : paras) {
					ps.setString(i++, para);
				}
			}
			ResultSet rs = ps.executeQuery();
			ResultSetMetaData rsmd = rs.getMetaData();
			int colcount = rsmd.getColumnCount();// 字段数
			StringBuilder sb = new StringBuilder("<root colcount='");
			sb.append(colcount);
			sb.append("'>");
			while (rs.next()) {
				sb.append("<node");
				for (i = 0; i < colcount; i++) {
					sb.append(" col" + i + "='");
					sb.append(rs.getString(i + 1));
					sb.append("'");
				}
				sb.append("></node>");
			}
			rs.close();
			rs = null;
			rsmd = null;
			sb.append("</root>");
			PrintWriter out = response.getWriter();
			out.write(sb.toString());
			out.close();
			// System.out.println(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("sql=" + sql);
		} finally {
			MyJDBC.close(myJDBC);
		}
	}
}
